#!/bin/bash
set -eux

remote_app=${JUJU_REMOTE_APP:-}
remote_unit=${JUJU_REMOTE_UNIT:-}
if [[ -n $remote_unit ]]; then
    juju-log -l INFO "remote unit $remote_unit"
    source=$remote_unit
else
    juju-log -l INFO "remote app $remote_app"
    source=$remote_app
fi

mkdir -p /var/run/appdata-sink
token=$(relation-get --app app-token "$source")
echo "$token" > /var/run/appdata-sink/token
if [[ -z "$token" ]]; then
  juju-log -l INFO "Waiting for token"
  status-set waiting "Waiting for token" || true
else
  juju-log -l INFO "Token is $token"
  status-set active "Token is $(echo "$token" | cut -c 1-30)" || true
fi
